package org.joy.util;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

public class ClassloaderUtility {

    private static final Logger LOGGER = Logger.getLogger(ClassloaderUtility.class.getName());

    private ClassloaderUtility(){
    }

    public static ClassLoader getCustomClassloader(String basePath, List<String> entries) throws MalformedURLException {
        List<URL> urls = new ArrayList<URL>();
        File file;

        if (entries != null) {
            for (String classPathEntry : entries) {
                String jarPath = (basePath + classPathEntry).replaceAll("%20", " ");
                file = new File(jarPath);
                LOGGER.fine("Loading jar : " + file.getPath());
                urls.add(file.toURI().toURL());
            }
        }

        ClassLoader parent = Thread.currentThread().getContextClassLoader();

        return new URLClassLoader(urls.toArray(new URL[urls.size()]), parent);
    }
    
    public static String getClassPath(){
        File f = new File(ClassloaderUtility.class.getProtectionDomain().getCodeSource().getLocation().getFile());
        String classPath = f.getParentFile().getPath() + File.separator;
        classPath = classPath.replaceAll("%20", " ");
        return classPath;
    }
    
}
